<template>
  <div class="boxd">
    <!-- <el-icon class="clone" @click="clone()">
      <CircleClose />
    </el-icon> -->
    <div ref="webgl" id="webgl" class="canvas" />
  </div>
</template>

<script setup>
import * as Three from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
// import { OBJLoader, MTLLoader } from "three-obj-mtl-loader";
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';

import { onMounted, reactive, ref } from 'vue';

const props = defineProps({
  modelUrl: {
    type: String
  }
})

const emit = defineEmits(['clone'])

// 场景
let scene = null

// const webgl = ref(null)
const state = reactive({
  // 相机
  camera: null,

  // 渲染器对象
  renderer: null,
  // 材质对象
  mesh: null,
  controls: null,
})

onMounted(() => {
  init()
})

const init = () => {
  let webgl = document.getElementById("webgl")
  // 相机位置
  // let width = window.innerWidth;
  // let height = window.innerHeight;
  const width = 600;
  const height = 400;
  // 创建场景
  scene = new Three.Scene();
  const k = width / height;
  const s = 1.6;
  state.camera = new Three.OrthographicCamera(-s * k, s * k, s, -s, 1, 1000);
  state.camera.position.set(80, 100, 60);
  state.camera.lookAt(new Three.Vector3(1, 80, 0));
  scene.add(state.camera);
  // 创建点光源
  // let light = new Three.DirectionalLight(0xffaaff);
  // light.position.set(80, 100, 50);
  // scene.add(light);
  //环境光
  const ambient = new Three.AmbientLight(0xffffff);
  scene.add(ambient);
  // 点光源
  // let point = new Three.PointLight(0xffffff);
  // point.position.set(400, 200, 300); // 点光源位置
  // scene.add(point); // 点光源添加到场景中
  // 创建渲染器
  state.renderer = new Three.WebGLRenderer({ antialias: true, alpha: true });
  state.renderer.setSize(width, height);
  state.renderer.setClearColor(0xfafafa); // 设置背景颜色
  webgl.appendChild(state.renderer.domElement);// 把画布插入到元素之中

  // 创建控件对象
  state.controls = new OrbitControls(state.camera, state.renderer.domElement);
  state.controls.addEventListener('change', animate);

  loadObj();

}
// 创建flb模型
const loadObj = () => {
  const gltfLoader = new GLTFLoader()
  gltfLoader.load(props.modelUrl, (obj) => {
    scene.add(obj.scene);
    animate();
  })
}

// 创建动画
const animate = () => {
  state.renderer.render(scene, state.camera);
}

// 关闭弹窗
const clone = () => {
  emit('clone')
}
</script>
<style lang="scss" scoped>
.boxd {
  width: 600px;
  height: 400px;
}

.clone {
  position: absolute;
  z-index: 1;
  font-size: 30px;
  cursor: pointer;
}

.clone:hover {
  color: #000;
  font-weight: 900;
}
</style>
